class User < ActiveRecord::Base
  has_many :authentications

  # Include default devise modules. Others available are:
  # :confirmable, :lockable and :timeoutable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :oauthable, :token_authenticatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :default_currency_code

  has_many :user_wallets, :dependent => :destroy
  has_many :wallets, :through => :user_wallets, :autosave => true
  has_many :operations, :dependent => :destroy, :order => "record_date DESC"
  has_many :scheduled_records, {
      :finder_sql =>
        '
          select *
            from scheduled_records
                 INNER JOIN wallets ON wallets.id = scheduled_records.wallet_id
                 INNER JOIN user_wallets ON user_wallets.wallet_id = wallets.id
            where user_wallets.user_id = #{id}
        '
  }

  has_many :wish_lists, :dependent => :destroy
  has_many :user_shops
  has_many :user_products

  before_create :create_default_user_stuff
  before_create :reset_authentication_token

  before_destroy :remove_wallet_links

  def remove_wallet_links
    #TODO
    # check that in case we delete user which have shared wallets with another user
    # we've been deleted and all records in user_wallets table
  end

  def wish_list
    @wish_list ||= self.wish_lists.first || WishList.default(self.id)
  end

  def default_wallet
    self.user_wallets.find(:first, :conditions => {:is_default_wallet => true}).wallet
  end

  def wallet_by_name(name = nil)
    return self.default_wallet if !name || name.blank?

    wallet = self.wallets.find_by_name(name)
    if wallet.nil?
      wallet = Wallet.create!(:name => name)
      self.user_wallets.build(:wallet => wallet, :is_default_wallet => true)
    end

    return wallet
  end

  def create_default_user_stuff
    w = Wallet.create!(:name => "default")
    self.user_wallets.build(:wallet => w, :is_default_wallet => true)
  end

  def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
    data = ActiveSupport::JSON.decode(access_token.get('https://graph.facebook.com/me?'))
    if user = User.find_by_email(data["email"])
      user
    else # Create an user with a stub password.
      User.create!(:email => data["email"], :password => Devise.friendly_token[0, 20])
    end
  end

  def apply_omniauth(omniauth)
    self.email = omniauth['user_info']['email'] if email.blank?
    authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
  end

  def password_required?
    (authentications.empty? || !password.blank?) && super
  end

  def tags
    # it can be done by sql query
    self.wallets.inject([]) {|tags, w| tags + w.tags}.sort {|a,b| b.operations_count <=> a.operations_count}
  end

  def currencies_codes
    self.wallets.inject([]) {|currencies, w| currencies + w.currencies_codes}
  end
end
